/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.SimpleError;
import org.apache.commons.lang.StringUtils;
import org.xptracker.domain.*;
import org.xptracker.persistence.Identified;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@UrlBinding("/Display.action")
public class DisplayActionBean extends StandardActionBean {
  private String id;
  public String getId() { return id; }
  public void setId(String id) { this.id = id; }

  public static final String DISPLAY = "/Display.action";
  private static Map<Class<? extends Identified>, String> resolutions = makeResolutions();

  private static Map<Class<? extends Identified>, String> makeResolutions() {
    Map<Class<? extends Identified>, String> resolutions = new LinkedHashMap<Class<? extends Identified>, String>();
    resolutions.put(Story.class, "/display/story.jsp");
    resolutions.put(StoryTask.class, "/display/task.jsp");
    resolutions.put(Task.class, "/display/task.jsp");
    resolutions.put(User.class, "/display/user.jsp");
    return resolutions;
  }

  public DisplayActionBean() {
  }

  @DefaultHandler
  public Resolution displayItem() {
    final History history = WikiActionBean.getHistory(getContext().getRequest().getSession());
    history.clear();
    history.push("item:" + id);
    RedirectResolution badResolution = new RedirectResolution(MainActionBean.HOME);
    try {
      if (StringUtils.isBlank(id)) {
        getContext().getValidationErrors().add("id", new SimpleError("ID is required."));
        return badResolution;
      }

      Identified item = domain.findEntity(resolutions.keySet(), id);
      if (item == null) {
        getContext().getValidationErrors().add("id", new SimpleError("No item with ID " + id + " could be found."));
        return badResolution;
      }

      return getResolution(item);
    } finally {
      badResolution.flash(this);
    }
  }

  private Resolution getResolution(Identified item) {
    ActionBeanContext ctx = getContext();
    HttpServletRequest request = ctx.getRequest();
    String res = getContext().getRequest().getParameter("destJsp");
    if (StringUtils.isBlank(res)) {
      res = resolutions.get(item.getClass());
    }

    if (StringUtils.isBlank(res)) {
      getContext().getValidationErrors().add("id", new SimpleError("Could not display item of type " +
          item.getClass().getName()));
      return new RedirectResolution(MainActionBean.HOME);
    }

    if (item instanceof Story) {
      String storyId = item.getId();
      item = domain.fetchStory(storyId);
      Story story = ((Story) item);
      User user = currentUserProvider.getCurrentUser();
      request.setAttribute("isTracker", story.isUserTrackingStory(user));
      request.setAttribute("canRemoveTracker", story.canRemoveTracker(user));
      List<StoryDescriptionSnapshot> snapshots = domain.listStorySnapshots(storyId);
      Collections.sort(snapshots, new Comparator<StoryDescriptionSnapshot>() {
        public int compare(StoryDescriptionSnapshot first, StoryDescriptionSnapshot second) {
          Date firstDate = first.getOccurred();
          Date secondDate = second.getOccurred();
          return secondDate.compareTo(firstDate);
        }
      });

      Iterator<StoryDescriptionSnapshot> iterator = snapshots.iterator();
      while (iterator.hasNext()) {
        StoryDescriptionSnapshot snapshot = (StoryDescriptionSnapshot) ((Iterator) iterator).next();
        if (StringUtils.equals(snapshot.getDescription(), story.getDescription()) &&
            StringUtils.equals(snapshot.getSummary(), story.getSummary())) {
          iterator.remove();
        }
      }
      request.setAttribute("storySnapshots", snapshots);
    }
    request.setAttribute("item", item);

    return new ForwardResolution(res);
  }
}
